package com.eshop.common.service.impl;

import org.slf4j.LoggerFactory;
import com.github.pagehelper.PageHelper;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Arrays;
import cn.hutool.core.collection.CollectionUtil;
import com.eshop.common.web.param.OrderQueryParam;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eshop.common.web.param.QueryParam;
import org.slf4j.Logger;
import com.eshop.common.service.BaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements BaseService<T>
{
    private static final Logger log;
    
    protected Page setPageParam(final QueryParam queryParam) {
        return this.setPageParam(queryParam, null);
    }
    
    protected Page setPageParam(final QueryParam queryParam, final OrderItem defaultOrder) {
        final Page page = new Page();
        page.setCurrent((long)queryParam.getPage());
        page.setSize((long)queryParam.getLimit());
        if (queryParam instanceof OrderQueryParam) {
            final OrderQueryParam orderQueryParam = (OrderQueryParam)queryParam;
            final List<OrderItem> orderItems = orderQueryParam.getOrders();
            if (CollectionUtil.isEmpty(orderItems)) {
                page.setOrders(Arrays.asList(defaultOrder));
            }
            else {
                page.setOrders(orderItems);
            }
        }
        else {
            page.setOrders(Arrays.asList(defaultOrder));
        }
        return page;
    }
    
    protected void getPage(final Pageable pageable) {
        String order = null;
        if (pageable.getSort() != null) {
            order = pageable.getSort().toString();
            order = order.replace(":", "");
            if ("UNSORTED".equals(order)) {
                order = "id desc";
            }
        }
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize(), order);
    }
    
    static {
        log = LoggerFactory.getLogger(BaseServiceImpl.class);
    }
}
